<template>
  <div class="channel-edit">
       <div class="channel">
      <van-cell title="我的频道" :border="false">
        <van-button plain size="mini" type="danger" @click="flag=!flag">{{flag?'取消':'编辑'}}</van-button>
      </van-cell>
      <van-grid>
        <van-grid-item v-for="(item,index) in channels" :key="item.id" @click="clickmychannels(item)"
         :class="{current:index===active}">
          <span>{{item.name}}</span>
          <van-icon name="close" color='#F46071' size="20" class="btn" v-if="flag && index !== 0" @click="clickDelChannel (item, index)"></van-icon>
        </van-grid-item>
      </van-grid>
    </div>
     <!-- 当前登陆用户没有订阅的频道 -->
    <div class="channel">
      <van-cell title="可选频道" :border="false"></van-cell>
      <van-grid>
        <van-grid-item v-for="item in optionalChannels" :key="item.id" @click="clickAddChannel(item)">
          <span>{{item.name}}</span>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState, mapGetters, mapMutations } from 'vuex'
import { reqSetChannels } from '@/api/channels.js'
export default {
  name: 'channelEdit',
  data () {
    return {
      flag: false
    }
  },

  props: ['active'],

  created () {
    this.getChannelAsync()
    this.getAllChannelAsync()
  },
  computed: {
    ...mapState(['channels', 'allchannels']),
    ...mapGetters(['optionalChannels'])

  },
  methods: {
    ...mapActions(['getChannelAsync', 'getAllChannelAsync']),
    ...mapMutations(['addChannels', 'delChannels']),
    clickmychannels (item) {
      this.$emit('update-curchannel', item)
    },
    async editChannels () {
      const channelList = this.channels.map((channel, index) => {
        return {
          id: channel.id,
          seq: index
        }
      })
      // 去掉推荐频道, 由于推荐频道是在第一个位置，所以这里直接删除第一个
      channelList.shift()
      // console.log(channelList)
      await reqSetChannels(channelList)
    },

    async clickAddChannel (item) {
      this.addChannels(item)
      this.editChannels()

      // console.log(res)
    },
    clickDelChannel (item, index) {
      if (this.active === index) {
        this.$emit('update-active', 0)
      }
      if (index < this.active) {
        this.$emit('update-active', this.active - 1)
      }
      this.delChannels(item)
      this.editChannels()
    }
  }

}
</script>

<style lang='scss' scoped>
.channel{
  padding:15px;
  font-size:14px;
  ::v-deep .van-button--mini {
    height: 22px;
    min-width: 50px;
  }
  .btn {
    position: absolute;
    top: 5px;
    right: 5px;
    font-size: 14px;
  }
}
.current {
  color: #e5615b;
  font-weight: bold;
}

</style>
